const orgStruct = require('./org-struct').init();
const curUserInfo = require('./cur-user-info').init();
const iframeDict = require('./iframe-dict').init();
/**
 * 数据可见程度度
 */
module.exports = class {
    constructor() {
        this.curUserInfo = curUserInfo;
        this.iframeDict = iframeDict;
        this.orgStruct = orgStruct;
    }

    static init() {
        return new this();
    }
    /**
     * 根据数据可视程度配置返回查询条件对象
     * @param {*} moduleId 模块ID
     * @param {*} userModel 用户信息模型
     * @param {*} keyMap key映射表
     * 固定key描述：{
     * partnersId:企业ID,
     * orgId:部门ID,
     * userId:用户ID,
     * areaCode:区域编码
     * }
     */
    async getDegree(moduleId, userModel, keyMap) {
        let dataOptions = "";
        let JsonObj = {};
        let moduleAble = null;
        if (!isNaN(moduleId) && moduleId > 0) {
            let userRuleAble = await this.curUserInfo.getUserRuleAble(userModel.UserRule, userModel.UserPartnersID);
            moduleAble = userRuleAble.find(item => {
                return item.M == moduleId
            });
        }

        if (moduleAble && moduleAble.D && moduleAble.D.value) {
            dataOptions = this.fixKeyMap(moduleAble.D.value, keyMap);
            let degreeModel = await this.trsport(dataOptions, userModel);
            if (degreeModel) {
                JsonObj = eval("(" + degreeModel + ")")
            }
        } else {
            let RuleDataDegreeCode = userModel.RuleDataDegreeCode ? userModel.RuleDataDegreeCode.split(',') : [];
            for (let code of RuleDataDegreeCode) {
                let dataDegree = this.iframeDict.GetDictItem('DataDegree', code);
                if (dataDegree && dataDegree.zd_Attr && dataDegree.zd_Attr != '') {
                    dataOptions = this.fixKeyMap(dataDegree.zd_Attr, keyMap);
                    let _degreeModel = await this.trsport(dataOptions, userModel);
                    let _JsonObj = eval("(" + _degreeModel + ")");
                    JsonObj = Object.assign(_JsonObj);
                }
            }
        }



        return JsonObj;
    }

    async trsport(dataOptions, userModel) {
        if (dataOptions.indexOf('[UserPartnersId]') > -1) {
            dataOptions = dataOptions.replace(/\[UserPartnersId\]/g, userModel.UserPartnersID);
        }
        if (dataOptions.indexOf('[UserOrgId]') > -1) {
            dataOptions = dataOptions.replace(/\[UserOrgId\]/g, `"${userModel.UserOrgStructID}"`);
        }
        if (dataOptions.indexOf('[UserID]') > -1) {
            dataOptions = dataOptions.replace(/\[UserID\]/g, userModel.UserID);
        }
        if (dataOptions.indexOf('[UserChildrenOrgIds]') > -1) { //部门下的所有部门

            let childrenOrgIds = this.orgStruct.getChildrensID(userModel.UserOrgStructID);
            childrenOrgIds.push(userModel.UserOrgStructID);
            dataOptions = dataOptions.replace(/\[UserChildrenOrgIds\]/g, JSON.stringify(childrenOrgIds));
        }
        if (dataOptions.indexOf('[UserPartnersOrgIds]') > -1) { //企业下的所有部门
            let ids = [];
            let OrgStructItems = this.orgStruct.getOrgStructItems(userModel.UserOrgStructID);
            for (let org of OrgStructItems) {
                ids.push(org.OS_ID);
            }
            dataOptions = dataOptions.replace(/\[UserPartnersOrgIds\]/g, JSON.stringify(ids));
        }
        if (dataOptions.indexOf('[UserChildrenUserIds]') > -1) {
            let ChildrenUser = await global.DataBase.iframe_user.Access.findAll({
                attributes: ['UserID'],
                where: {
                    UserParentIDs: {
                        "$like": userModel.UserParentIDS + ',' + userModel.UserID + '%'
                    }
                },
                raw: true
            });
            let userIds = [];
            ChildrenUser.map(function (item) {
                userIds.push(item.UserID);
            })
            dataOptions = dataOptions.replace(/\[UserChildrenUserIds\]/g, JSON.stringify(ChildrenUserIds));
        }

        if (dataOptions.indexOf('[UserChildrenArea]') > -1) {
            let childrenArea = this.iframeDict.getChildrenValues("area", userModel.UserAreaCode);
            childrenArea.push(userModel.UserAreaCode);
            dataOptions = dataOptions.replace(/\[UserChildrenArea\]/g, JSON.stringify(childrenArea));
        }

        return dataOptions;
    }

    fixKeyMap(dataOptions, keyMap) {
        if (!keyMap) return dataOptions;

        /* 将默认的键替换为keyMap中的value*/
        for (let key in keyMap) {
            if (key) {
                dataOptions = dataOptions.replace(key + ":", keyMap[key] + ":");
            }
        }
        /*只留下KeyMap中定义的key*/
        let dataOpts = dataOptions.replace('{', '').replace('}', '').split(',');
        for (let i = dataOpts.length - 1; i >= 0; i--) {
            let isHas = false;
            for (let key in keyMap) {
                if (dataOpts[i].indexOf(keyMap[key] + ':') > -1) {
                    isHas = true;
                }
            }
            if (!isHas) {
                dataOpts.splice(i, 1);
            }
        }
        return `{${dataOpts.join(',')}}`;
    }
}